import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class ProcessCart
 */
public class ProcessCart extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String rTypeAddItem = "a";
	private static final String rTypeRemItem = "r";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ProcessCart() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		String requestType = request.getParameter("typ");

		if (requestType != null) {
			HashMap<Integer, Integer> products = (HashMap) session
					.getAttribute("mapje");
			if (products == null) {
				products = new HashMap<Integer, Integer>();
			}
			if (requestType.equals(rTypeAddItem)) {
				int pId = Integer.parseInt(request.getParameter("pId"));
				int amount = Integer.parseInt(request.getParameter("amo"));
				products.put(pId, amount);
			} else if (requestType.equals(rTypeRemItem)) {
				int pId = Integer.parseInt(request.getParameter("pId"));
				products.remove(pId);
			}
			session.setAttribute("mapje", products);
			
//			String referer = request.getHeader("referer");
//			String encodedRef = response.encodeURL(referer);
//			PrintWriter out = response.getWriter();
//			out.println("ref: '" + referer + "'");
//			out.println("encoded: '" + encodedRef + "'");
//			response.sendRedirect(encodedRef);
		} else {
			PrintWriter out = response.getWriter();
			HashMap<Integer, Integer> products = (HashMap) session
					.getAttribute("mapje");
			if (products != null) {
				out.println("<html><body>" + products.toString()
						+ "</body></html>");
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
